<?php

namespace App\Http\Controllers\Admin\Client;

use App\Exports\PriceExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\client\PriceRequest;
use App\Imports\PriceImport;
use App\Models\client\PriceDetailModel;
use App\Models\client\PriceModel;
use App\Models\FlightItemModel;
use App\Models\OrderModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Price extends Controller
{
    use PriceRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $route_id = $request->input('route_id', '');
        $goods_attr = $request->input('goods_attr', '');
        $flight_id = $request->input('flight_id', '');
        $customer_id = $request->input('customer_id', '');

        $query = PriceModel::query()->with(['create_admin', 'currency', 'customer', 'detail']);
//        ->withWhereHas('detail', function ($query) use ($route_id, $goods_attr) {
//            if($route_id){
//                $query->where('route_id', $route_id);
//            }
//
//            if($goods_attr){
//                $query->where('goods_attr', $goods_attr);
//            }
//        });

        if($customer_id){
            $query->where('customer_id', $customer_id);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'customer_id' => $item->customer_id,
                'customer_name' => $item->customer ? $item->customer->name : '',
//                'route_id' => $item->route_id,
//                'route_name' => $item->route ? $item->route->code : '',
//                'goods_attr' => $item->goods_attr,
//                'goods_attr_name' => $item->goods_attr == 1 ? '普货' : '特货',
                'currency_id' => $item->currency_id,
                'currency_name' => $item->currency ? $item->currency->short_code : '',
                'effect_date' => $item->effect_date,
//                'flight_id' => $item->flight_id,
//                'flight_number' => $item->flight ? $item->flight->flight_number : '',
                'remark' => $item->remark,
                'detail' => $item->detail,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name: '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        DB::beginTransaction();
        try {
            $model = new PriceModel();
            $model->customer_id  = $params['customer_id'];
            $model->currency_id  = $params['currency_id'];
            $model->effect_date  = $params['effect_date'];
            $model->remark  = $params['remark'] ?? '';
            $model->created_admin_id  = $auth->id;
            $model->save();

            foreach ($params['detail'] as $value){
                $detail = new PriceDetailModel();
                $detail->price_id = $model->id;
                $detail->customer_id  = $params['customer_id'];
                $detail->route_id  = $value['route_id'];
                $detail->goods_attr  = $value['goods_attr'];
                $detail->price45 = $value['price45'];
                $detail->price100 = $value['price100'];
                $detail->price300 = $value['price300'];
                $detail->price500 = $value['price500'];
                $detail->price1000 = $value['price1000'];
                $detail->validity  = $value['validity'];
                $detail->remark  = $value['remark'];
                $detail->save();
            }

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }


        return $this->success();
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = PriceModel::find($id);
        if(!$model) {
            return $this->error('数据不存在');
        }

        DB::beginTransaction();
        try {
            $model->customer_id  = $params['customer_id'];
            $model->currency_id  = $params['currency_id'];
            $model->effect_date  = $params['effect_date'];
            $model->remark  = $params['remark'] ?? '';
            $model->save();

            PriceDetailModel::where('price_id', $id)->delete();

            foreach ($params['detail'] as $value){
                $detail = new PriceDetailModel();
                $detail->price_id = $model->id;
                $detail->customer_id  = $params['customer_id'];
                $detail->route_id  = $value['route_id'];
                $detail->goods_attr  = $value['goods_attr'];
                $detail->price45 = $value['price45'];
                $detail->price100 = $value['price100'];
                $detail->price300 = $value['price300'];
                $detail->price500 = $value['price500'];
                $detail->price1000 = $value['price1000'];
                $detail->validity  = $value['validity'];
                $detail->remark  = $value['remark'];
                $detail->save();
            }

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function delete(int $id){
        $model = PriceModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        PriceDetailModel::where('price_id', $id)->delete();
        return $this->success();
    }

    /**
     * Notes:报价详情
     * User: xiangzi
     * Date: 2025/6/19
     * Time: 上午11:29
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(){
        $id = request()->get('id', 0);
        $model = PriceModel::find($id);
        if(!$model) {
            return $this->error('报价不存在');
        }

        $detail = PriceDetailModel::with('route')->where('price_id', $id)->get();

        $list = $detail->map(function($item) {
            $res = [
                'id' => $item->id,
                'route_id' => $item->route_id,
                'route_name' => $item->route ? $item->route->code : '',
                'goods_attr' => $item->goods_attr,
                'goods_attr_name' => $item->goods_attr == 1 ? '普货' : '特货',
                'price45' => $item->price45,
                'price100' => $item->price100,
                'price300' => $item->price300,
                'price500' => $item->price500,
                'price1000' => $item->price1000,
                'validity' => $item->validity,
                'remark' => $item->remark,
            ];
            return $res;
        });

        return $this->success(['list' => $list]);

    }


    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = PriceModel::query()->with(['create_admin', 'detail', 'route', 'currency', 'customer']);
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $customer_name = $item->customer->name ?? '';
            $currency_name = $item->currency->short_code ?? '';
            $effect_date = $item->effect_date;

            $res = $item->detail->map(function($detail) use ($customer_name, $currency_name, $effect_date) {
                return [
                    'customer_name' => $customer_name,
                    'route_name' => $detail->route ? $detail->route->code : '',
                    'goods_attr_name' => $detail->goods_attr == 1 ? '普货' : '特货',
                    'price45' => $detail->price45,
                    'price100' => $detail->price100,
                    'price300' => $detail->price300,
                    'price500' => $detail->price500,
                    'price1000' => $detail->price1000,
                    'currency_name' => $currency_name,
                    'effect_date' => $effect_date,
                    'validity' => $detail->validity,
                    'remark' => $detail->remark,
                ];
            });
            return $res;
        });

        $file_name = '报价单-'.date('Ymd').'.xlsx';

        return Excel::download(new PriceExport($list), $file_name);
    }

    public function import(Request $request)
    {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file) {
            return $this->error('请选择文件');
        }

        $import = new PriceImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            $prices = [];
            foreach ($lines as $line){

                if(isset($prices[$line['customer_id']])){
                    $prices[$line['customer_id']]['detail'][] = [
                            'route_id' => $line['route_id'],
                            'goods_attr' => $line['goods_attr'],
                            'price45' => $line['price45'],
                            'price100' => $line['price100'],
                            'price300' => $line['price300'],
                            'price500' => $line['price500'],
                            'price1000' => $line['price1000'],
                            'validity' => $line['validity'],
                            'remark' => $line['remark'],
                        ];
                }else{
                    $prices[$line['customer_id']] = [
                        'customer_id' => $line['customer_id'],
                        'currency_id' => $line['currency_id'],
                        'effect_date' => $line['effect_date'],
                        'detail' => [
                            [
                                'route_id' => $line['route_id'],
                                'goods_attr' => $line['goods_attr'],
                                'price45' => $line['price45'],
                                'price100' => $line['price100'],
                                'price300' => $line['price300'],
                                'price500' => $line['price500'],
                                'price1000' => $line['price1000'],
                                'validity' => $line['validity'],
                                'remark' => $line['remark'],
                            ]
                        ]
                    ];
                }


//                $price = new PriceModel();
//                $price->customer_id  = $line['customer_id'];
//                $price->route_id  = $line['route_id'];
//                $price->goods_attr  = $line['goods_attr'];
//                $price->currency_id  = $line['currency_id'];
//                $price->effect_date  = $line['effect_date'];
//                $price->flight_id  = $line['flight_id'];
//                $price->remark  = $line['remark'] ?? '';
//                $price->created_admin_id  = $auth->id;
//                $price->save();
//
//                foreach ($line['detail'] as $detail){
//                    $price_detail = new PriceDetailModel();
//                    $price_detail->price_id  = $price->id;
//                    $price_detail->weight_from  = $detail['weight_from'];
//                    $price_detail->weight_to  = $detail['weight_to'];
//                    $price_detail->price  = $detail['price'];
//                    $price_detail->save();
//                }
            }

            foreach ($prices as $value){
                $price = new PriceModel();
                $price->customer_id  = $value['customer_id'];
                $price->currency_id  = $value['currency_id'];
                $price->effect_date  = $value['effect_date'];
                $price->created_admin_id  = $auth->id;
                $price->save();

                foreach ($value['detail'] as $detail){
                    $price_detail = new PriceDetailModel();
                    $price_detail->price_id  = $price->id;
                    $price_detail->customer_id  = $value['customer_id'];
                    $price_detail->route_id  = $detail['route_id'];
                    $price_detail->goods_attr  = $detail['goods_attr'];
                    $price_detail->price45  = $detail['price45'];
                    $price_detail->price100  = $detail['price100'];
                    $price_detail->price300  = $detail['price300'];
                    $price_detail->price500  = $detail['price500'];
                    $price_detail->price1000  = $detail['price1000'];
                    $price_detail->validity  = $detail['validity'];
                    $price_detail->remark  = $detail['remark'];
                    $price_detail->save();
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

    /**
     * Notes:获取单价
     * User: xiangzi
     * Date: 2025/5/30
     * Time: 下午1:56
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_price(Request $request){
        $params = $request->all();
        $take_order_sn = $params['sn'] ?? '';
        $customer_id = $params['customer_id'] ?? '';
        $flight_id = $params['flight_id'] ?? '';
        $weight = $params['weight'] ?? 0;

        if(!$weight){
            return $this->error('重量不能为空');
        }

        $take_order = TakeOrderModel::query()->where('sn', $take_order_sn)->first();

        if(!$take_order){
            return $this->error('提单不存在');
        }

        $flight_item = FlightItemModel::where('flight_id', $flight_id)->first();
        if(!$flight_item){
            return $this->error('没有找到航线');
        }

        $route_id = $flight_item->route_id;

        $order = OrderModel::query()->where('take_order_id', $take_order->id)->first();

        if(!$order && $order->goods_attr){
            return $this->error('无法确认货物属性');
        }

        $price = PriceModel::where('customer_id', $customer_id)->first();

        if(!$price){
            return $this->error('没有找到对应客户报价');
        }

        $price_detail = PriceDetailModel::query()
            ->where('price_id', $price->id)
            ->where('route_id', $route_id)
            ->where('goods_attr', $order->goods_attr)
            ->first();

        if(!$price_detail){
            return $this->error('没有找到对应航线报价');
        }

        if($weight > 1000){
            $price = $price_detail->price1000;
        }else if ($weight > 500){
            $price = $price_detail->price500;
        }else if ($weight > 300){
            $price = $price_detail->price300;
        }else if ($weight > 100){
            $price = $price_detail->price100;
        }else if ($weight > 45){
            $price = $price_detail->price45;
        }else{
            $price = 0;
        }

        return $this->success([
            'price' => $price,
            'currency' => $price->currency->symbol ?? '',
        ]);
    }


}
